package cn.kgc.comment.controller;

import cn.kgc.comment.service.CommentService;
import cn.kgc.common.entity.Comment;
import cn.kgc.common.entity.DataPage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by teacher ZHANG on 2023/2/1
 */
@RestController
public class CommentController {
    @Autowired
    private CommentService commentService;

    @GetMapping("/comments")
    public DataPage<Comment> listComments(Integer articleId, Integer pageNum, Integer pageSize) {
        //查询条件包装类
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("articleId", articleId);
        wrapper.orderByDesc("createTime");

        //m-plus分页
        IPage<Comment> pageInfo = new Page<>(pageNum, pageSize);
        commentService.page(pageInfo, wrapper);

        DataPage<Comment> dataPage = new DataPage<>();
        dataPage.setDataList(pageInfo.getRecords());
        dataPage.setRowCount((int)pageInfo.getTotal());
        dataPage.setPageCount((int)pageInfo.getPages());
        dataPage.setPageNum(pageNum);
        dataPage.setPageSize(pageSize);

        return dataPage;
    }

    @PostMapping("/comments")
    public Boolean saveComment(@RequestBody Comment comment) {
        return commentService.saveComment(comment) > 0;
    }

    @DeleteMapping("/comments/{commentId}")
    public Boolean removeComment(@PathVariable("commentId") Integer commentId) {
        return commentService.removeById(commentId);
    }

    //返回评论量
    @GetMapping("/comments/count")
    public List<Map<String, Object>> listCommentsCount(String articleIds, Integer topNum) {
        if (articleIds == null) {
            return commentService.listTopComments(topNum);
        }

        String[] cids = articleIds.split(",");

        List<Integer> list = new ArrayList<>();
        for (String cid : cids) {
            list.add(Integer.parseInt(cid));
        }

        return commentService.listCounts(list);
    }
}
